<template>
  <div id="uploadAvatar">
    <div class="avatar-uploader-box">
      <el-upload :multiple="false" ref="upload" :action="uploadurl" :show-file-list="false"
                 :on-success="handleAvatarSuccess" :on-error="handleAvatarError" :before-upload="beforeAvatarUpload"
                 :on-change="changeAvatarUpload" :auto-upload="false">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <div class="avatar_upload-btn-box">
      <el-button class="avatar_upload-btn" type="primary" @click="uploadAvatarToService">上传照片</el-button>
    </div>
  </div>
</template>

<script>
  import { createUploadUrl } from '../../assets/js/post.js'

  export default {
    name: 'uploadAvatar',
    props: ['config'],
    data () {
      return {
        imageUrl: '',
        uploadurl: ''
      }
    },
    created () {
      this.uploadurl = createUploadUrl(this.config.type)
    },
    methods: {
      handleAvatarSuccess (res, file) {
        if (res.status === 0) {
          this.$message.success('上传成功！')
        } else {
          this.$message.error(res.message)
        }
        this.$emit('getUploadResponse', res)
      },
      handleAvatarError (err, file, fileList) {
        this.$message.error('上传失败！')
      },
      changeAvatarUpload (file) {
        this.imageUrl = URL.createObjectURL(file.raw)
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
          return false
        }
        return true
      },
      uploadAvatarToService () {
        this.$refs.upload.submit()
      }
    }
  }
</script>

<style scoped>
  /*图片上传*/
  .avatar-uploader-box {
    background-color: #eaedf1;

    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader-box:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: white;
    width: 178px;
    height: 220px;
    line-height: 220px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 220px;
    display: block;
  }

  .avatar_upload-btn-box {
    margin-top: 1em;
    width: 178px;
    text-align: center;
  }

  .avatar_upload-btn {
    width: 150px;
  }
</style>
